package ms.platform.system.controller;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import ms.platform.system.model.Menu;
import ms.platform.system.model.Resource;
import ms.platform.system.model.RoleResource;
import ms.platform.system.service.ResourceService;

@Controller
@RequestMapping("/system/resource/")
public class ResourceController extends BaseController {
	
	@Autowired
	private ResourceService resourceService;
	
	/**
	 * 资源列表
	 * @return
	 */
	@RequestMapping(value = "/list")
	public String resourceList(HttpServletRequest request){
		List<Resource> resourceAllList = resourceService.queryResourceList();
		List<Menu> list=new ArrayList<Menu>();
    	if(resourceAllList != null && resourceAllList.size() > 0){
    		for(Resource resource : resourceAllList){
    			String name = resource.getName();
    			Integer id = resource.getId();
    			Integer parentId = resource.getParentId();
    			Menu menu = new Menu(id, name, parentId, resource.getIsUsed(), resource.getPath(),resource.getLevel());
    			list.add(menu);
    		}
    	}
    	
    	this.createTree(list);
		request.setAttribute("menuList", list);
		return "system/resource/list";
	} 
	
	/**
	 * 分配权限
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/toAllotResource")
	public String toAllotResource(Integer roleId, HttpServletRequest request){
		
		List<Resource> resourceAllList = resourceService.queryUsedResourceList(); //查询所有启用资源列表
    	List<Resource> resourceList = resourceService.queryResourceByRole(roleId); //根据roleId查询该角色的权限列表
    	
		Map<Integer, Resource> resourceMap = new HashMap<>();
		for (Resource resource:resourceList) {
			resourceMap.put(resource.getId(), resource);
		}
		
		List<Menu> list=new ArrayList<Menu>();
    	if(resourceAllList != null && resourceAllList.size() > 0){
    		for(Resource resource : resourceAllList){
    			String name = resource.getName();
    			Integer id = resource.getId();
    			Integer parentId = resource.getParentId();
    			Menu menu = new Menu(id, name, parentId, resource.getIsUsed(), "",resource.getLevel());
    			if(resourceMap.get(resource.getId()) != null){
    				menu.setIsChecked(true);
    			}
    			list.add(menu);
    		}
    	}
    	
    	this.createTree(list);
	    request.setAttribute("menuList", list);
	    request.setAttribute("roleId", roleId);
	    return "system/role/detail";
	}
	
	/**
	 * 组成树形菜单结果
	 * @param list
	 */
	public void createTree(List<Menu> list) {
		int lowLevel = list.get(0).getLevel();
		List<Menu> children = new ArrayList<Menu>();
		// 当等级最高时，停止排序
		if (lowLevel != 1) {
			// 将最低级别的放到数组中
			for (Menu menu : list) {
				if (menu.getLevel() == lowLevel) {
					children.add(menu);
				} else {
					break;
				}
			}
			// 增加遍历效率
			list.removeAll(children);
			for (Menu child : children) {
				for (Menu parent : list) {
					if (parent.getId().equals(child.getParentId())) {
						parent.addChildren(child);
					}
				}
			}
			createTree(list);
		}

	}

	
	/**
	 * 跳转到修改资源页面
	 * @param role
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/toEdit")
	@ResponseBody
	public Object toEditResource(Integer id,HttpServletRequest request){
		Resource resource=null;
		if(id!=null){
			resource=resourceService.queryResourceById(id);
		}
		return returnSuccess("返回成功", resource);
	}
	
	/**
	 * 保存或者修改资源
	 * @param role
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/save")
	@ResponseBody
	public Object saveOrUpdateResource(Resource resource,HttpServletRequest request){
		if(resource.getId() != null){
			resourceService.updateResource(resource);
		}else{
			resourceService.insertResource(resource);
			Integer id=resource.getId();
			Resource resourceP=resourceService.queryResourceById(resource.getParentId());
			if(resourceP!=null){
				if(resource.getParentId().equals("0")){
					resource.setPath("/"+id+"/");
				}else{
					resource.setPath(resourceP.getPath()+id+"/");
				}
			}else{
				resource.setPath("/"+id+"/");
			}
			resource.setOrder(id);
			resourceService.updateResource(resource);
		}
		return returnSuccess("操作成功", resource);
	}
	
	/**
	 * 禁用|启用菜单
	 * @param resource
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/disabledResource")
	@ResponseBody
	public Object disabledResource(Resource resource, HttpServletRequest request){
		resourceService.disabledResource(resource);
		return returnSuccess("操作成功",resource);
	}
	
	
	@RequestMapping(value = "/deleteResource")
	@ResponseBody
	public Object deleteResource(Integer id, HttpServletRequest request){
		resourceService.deleteResourceById(id);
		return returnSuccess("操作成功","");
	}
	
	@RequestMapping(value = "/allotResource")
	@ResponseBody
	public Object allotResource(RoleResource rr,HttpServletRequest request){
		 if(rr!=null && rr.getResourceIds()!=null){ 
			String[] ayy=rr.getResourceIds().split(",");
			
			
			/*
			 * 这里需要把登录，退出，首页等默认必须有的菜单放进去
			 */
			List<Integer> resourceId = resourceService.queryResourceIdList();
			List<String> ayyList = new ArrayList<String>(Arrays.asList(ayy));//把arr转数组，方便添加元素
			for (Integer id : resourceId) {
				ayyList.add(id + "-1");
			}
			ayy = (String[]) ayyList.toArray(new String[0]);
			
			
			for (int i = 0; i < ayy.length; i++) {
				String[] r=ayy[i].split("-");
				Integer type=Integer.valueOf(r[1]);
				Integer id=Integer.valueOf(r[0]);
				rr.setResourceId(id);
				if(type==1){
					if(this.resourceService.queryRoleResource(rr).size()==0){
						this.resourceService.insertRoleResource(rr);
					}
				}else if(type==0){
					this.resourceService.deleteRoleResource(rr);
				}
			}
			
		}
		return returnSuccess("分配成功", null);
	}
	
	
	/*@RequestMapping(value = "/orderResource")
	@ResponseBody
	public Object orderResource(Integer id, Integer orderId,HttpServletRequest request){
		//目标互换资源
		Resource resource1 = this.resourceService.queryResourceById(orderId);
		Integer order1=resource1.getOrder();
		
		//本资源
		Resource resource2 =this.resourceService.queryResourceById(id);
		Integer order2=resource2.getOrder();
		
		//交换order的值
		resource1.setOrder(order2);
		resource2.setOrder(order1);
		
		//修改资源
		this.resourceService.updateResource(resource1);
		this.resourceService.updateResource(resource2);
		return returnSuccess("操作成功", null);
	}*/
	
}
